package com.tange.ai.iot.client.gnssa.utils

import java.nio.ByteBuffer
import java.nio.ByteOrder

object HexConverter {
    /**
     * 将十进制数转换为指定字节长度的大端十六进制字符串
     * @param value 十进制数值
     * @param byteSize 字节长度 (1, 2, 4, 8)
     */
    fun toBigEndianHex(value: Long, byteSize: Int): String {
        validateByteSize(byteSize)
        val buffer = ByteBuffer.allocate(byteSize).order(ByteOrder.BIG_ENDIAN)
        putValue(buffer, value, byteSize)
        return bytesToHex(buffer.array())
    }

    /**
     * 将十进制数转换为指定字节长度的小端十六进制字符串
     * @param value 十进制数值
     * @param byteSize 字节长度 (1, 2, 4, 8)
     */
    fun toLittleEndianHex(value: Long, byteSize: Int): String {
        validateByteSize(byteSize)
        val buffer = ByteBuffer.allocate(byteSize).order(ByteOrder.LITTLE_ENDIAN)
        putValue(buffer, value, byteSize)
        return bytesToHex(buffer.array())
    }

    /**
     * 将十进制数转换为大端字节数组
     * @param value 十进制数值
     * @param byteSize 字节长度 (1, 2, 4, 8)
     */
    fun toBigEndianBytes(value: Long, byteSize: Int): ByteArray {
        validateByteSize(byteSize)
        return ByteBuffer.allocate(byteSize)
            .order(ByteOrder.BIG_ENDIAN)
            .apply { putValue(this, value, byteSize) }
            .array()
    }

    /**
     * 将十进制数转换为小端字节数组
     * @param value 十进制数值
     * @param byteSize 字节长度 (1, 2, 4, 8)
     */
    fun toLittleEndianBytes(value: Long, byteSize: Int): ByteArray {
        validateByteSize(byteSize)
        return ByteBuffer.allocate(byteSize)
            .order(ByteOrder.LITTLE_ENDIAN)
            .apply { putValue(this, value, byteSize) }
            .array()
    }

    // 内部方法：根据字节长度将值放入缓冲区
    private fun putValue(buffer: ByteBuffer, value: Long, byteSize: Int) {
        when (byteSize) {
            1 -> buffer.put(value.toByte())
            2 -> buffer.putShort(value.toShort())
            4 -> buffer.putInt(value.toInt())
            8 -> buffer.putLong(value)
        }
    }

    // 验证字节长度是否合法
    private fun validateByteSize(byteSize: Int) {
        if (byteSize !in listOf(1, 2, 4, 8)) {
            throw IllegalArgumentException("Invalid byte size. Supported sizes: 1, 2, 4, 8")
        }
    }

    // 字节数组转十六进制字符串
    private fun bytesToHex(bytes: ByteArray): String {
        val hexChars = CharArray(bytes.size * 2)
        for (i in bytes.indices) {
            val v = bytes[i].toInt() and 0xFF
            hexChars[i * 2] = "0123456789ABCDEF"[v ushr 4]
            hexChars[i * 2 + 1] = "0123456789ABCDEF"[v and 0x0F]
        }
        return String(hexChars)
    }
}